import { create, StateCreator } from "zustand";
import { persist } from "zustand/middleware";
import { theme } from "antd";

export type ThemeState = "light" | "dark" | "system";
type Theme = "light" | "dark";
interface State {
  theme: "dark" | "light";
  themeState: ThemeState;
  algorithm: typeof theme.defaultAlgorithm;
}
interface Actions {
  changeTheme: (theme: State["themeState"]) => void;
}

const creator: StateCreator<State & Actions> = set => ({
  theme: "light",
  themeState: "light",
  algorithm: theme.defaultAlgorithm,
  changeTheme: val => {
    const root = document.documentElement;
    root.classList.remove("light", "dark");
    let finalTheme: Theme;
    if (val === "system") {
      const sysIsDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
      finalTheme = sysIsDark ? "dark" : "light";
    } else {
      finalTheme = val;
    }
    
    root.classList.add(finalTheme);

    set({
      theme: finalTheme,
      themeState: val,
      algorithm: finalTheme === 'dark' ? theme.darkAlgorithm : theme.defaultAlgorithm,
    });
  },
});

export const useThemeConf = create<State & Actions>()(persist(creator, { name: "themeConf" }));
